#coding=utf-8
'''
Created on 2013年9月2日

@author: xuben

日志记录
'''

import chardet
import logging
import traceback

LOGGER_COMMON = "common"
LOGGER_SOCKET = "socket"
LOGGER_LOGIN = "login"
LOGGER_ERROR = "error"

_log_path = 'log/'

#初始化配置
def init(path):
    global _log_path
    _log_path = path
    initLogger(LOGGER_COMMON)
    initLogger(LOGGER_SOCKET)
    initLogger(LOGGER_LOGIN)
    initLogger(LOGGER_ERROR)
    
def log(msg, logger_name = "common", output = False, needDec = True):
    try:
        if not isinstance(msg, unicode) and needDec:
            #等价于msg = msg.decode('utf-8')
            #unicode各编码之间转换的中间体，比如utf-8转gbk为str.decode('utf-8').encode('gbk')
            encoding = getEncoding(msg)
            msg = unicode(msg, encoding)
        if output:
            print msg
        logger = logging.getLogger(logger_name)
        logger.info(msg)
    except:
        logException()

'''
获取编码方式
'''
def getEncoding(msg):
    encodingInfo = chardet.detect(msg)
    return encodingInfo['encoding']

'''
记录异常
'''        
def logException():
    logger = logging.getLogger(LOGGER_ERROR)
    logger.error(traceback.format_exc())
#     logger.error(traceback.format_exception(*sys.exc_info()))
    logger.error(traceback.format_stack())
    
def initLogger(name):
    fs = '%(asctime)s %(levelname)s %(message)s'
    dfs = '%y-%m-%d %H:%M:%S'
    fmt = logging.Formatter(fs, dfs)

    logger = logging.getLogger(name)
    hdlr = logging.FileHandler(_log_path+'log-' + name + '.txt', 'w')
    hdlr.setFormatter(fmt)
    logger.addHandler(hdlr)
    logger.setLevel(logging.DEBUG)
    logger.info('开启日志记录')